<?php


class WSB_Collection2 implements Iterator, Countable
{
    /**
     * @var integer
     */
    protected $_count;

    /**
     * @var array
     */
    protected $_data;

    /**
     * @var string
     */
    protected $_modelClass = 'WSB_Model2';

    /**
     * @var WSB_DbMapper
     */
    protected $_mapper;

    /**
     * Constructor
     *
     * @param array|object $data
     */
    public function __construct($data)
    {
        if(is_object($data)) {
            $data = (array)$data;
        }
        if(!is_array($data)) {
            throw new Exception('Collection2::__construct(): Initial data must be an array or object');
        }
        $this->_data = $data;
        $this->_count = count($this->_data);
        $this->init();
    }

    /**
     * @param string $modelClass
     */
    public function setModelClass($modelClass)
    {
    	$this->_modelClass = $modelClass;
    }

    /**
     * @param array $item
     */
    public function add(array $item)
    {
        $this->_data[] = $item;
        $this->_count = count($this->_data);
    }

    /**
     * Initialize object
     *
     * Called from {@link __construct()} as final step of object instantiation.
     *
     * @return void
     */
    public function init()
    {
    }

    /**
     * Set mapper
     *
     * @param WSB_DbMapper $mapper
     * @return void
     */
    public function setMapper(WSB_DbMapper $mapper)
    {
        $this->_mapper = $mapper;
    }

    /**
     * Get mapper
     *
     * @return WSB_DbMapper
     */
    public function getMapper()
    {
        return $this->_mapper;
    }

    /**
     * @return void
     */
    public function reverse()
    {
    	$this->_data = array_reverse($this->_data);
    }

    /**
     * @return integer
     */
    public function count()
    {
        return $this->_count;
    }

    /**
     * @return WSB_Model2
     */
    public function current()
    {
    	$current = current($this->_data);
    	return new $this->_modelClass($current);
    }

    /**
     * @return integer
     */
    public function key()
    {
        return key($this->_data);
    }

    /**
     * @return array
     */
    public function next()
    {
        return next($this->_data);
    }

    /**
     * @return array
     */
    public function rewind()
    {
        return reset($this->_data);
    }

    /**
     * @return boolean
     */
    public function valid()
    {
    	return array_key_exists($this->key(), $this->_data);
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return $this->_data;
    }

    /**
     * @todo
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->_data);
    }

    /**
     * @todo
     * @return string
     */
    public function toXml()
    {
    }

}

